package com.service.thirddatacenter.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * <p>
 *  @desc
 */
@Component
public class I18nUtil {

    private static MessageSource messageSource;

    /**
     * 语言
     */
    public static class CLocale {
        public static final String zh_CN = "zh_CN";
        public static final String zh_TW = "zh_TW";
        public static final String en_US = "en_US";
        public static final String ja_JP = "ja_JP";
        public static final String ko_KO = "ko_KO";

        public static boolean contain(String lang) {
            if (StringUtils.equals(lang, zh_CN)
                    || StringUtils.equals(lang, zh_TW)
                    || StringUtils.equals(lang, en_US)
                    || StringUtils.equals(lang, ja_JP)
                    || StringUtils.equals(lang, ko_KO)) {
                return true;
            }
            return false;
        }
    }

    /**
     * 初始化工具并且自动注入对象
     */
    @Autowired
    private void init(@Qualifier("messageSource") MessageSource ms) {
        //初始化静态属性
        I18nUtil.messageSource = ms;
    }

    /**
     * @param key
     * @return
     */
    public static String getMessage(String key) {
        if (key == null) {
            return null;
        }
        Locale locale = LocaleContextHolder.getLocale();
        try {
            return messageSource.getMessage(key, null, locale);
        } catch (NoSuchMessageException e) {
            return key;
        }
    }

    /**
     * @param key
     * @param local
     * @return
     */
    public static String getMessage(String key, String local, Object... args) {
        Locale locale = new Locale(local);
        return messageSource.getMessage(key, args, locale);
    }

}